﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Egg;

namespace Coder
{
    public static class SystemOpreator
    {

        private static Dictionary<string, string> dicts;

        static SystemOpreator()
        {
            dicts = new Dictionary<string, string>();
        }

        /// <summary>
        /// 对象转换为字典
        /// </summary>
        /// <param name="obj">待转化的对象</param>
        /// <returns></returns>
        public static Dictionary<string, string> ObjectToMap(object obj)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            Type t = obj.GetType(); // 获取对象对应的类， 对应的类型
            PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 获取当前type公共属性
            foreach (PropertyInfo p in pi)
            {
                if (p is null) continue;
                var value = p.GetValue(obj);
                // 进行判NULL处理
                if (value is null) continue;
                map.Add(p.Name, value.ToString() ?? ""); // 向字典添加元素
            }
            return map;
        }

        /// <summary>
        /// 获取闭合路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetClosePath(string path)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (path.EndsWith("\\")) return path;
                return path + "\\";
            }
            if (path.EndsWith("/")) return path;
            return path + "/";
        }

        /// <summary>
        /// 设置内容
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set(string key, string value)
        {
            dicts[key] = value;
            //if (Program.DebugMode) Console.WriteLine($"[Debug] System.Set {key} : \"{value}\"");
        }

        /// <summary>
        /// 获取内容
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetContent(string key)
        {
            // 优先使用字典
            if (dicts.ContainsKey(key)) return dicts[key];
            // 获取固定变量
            switch (key)
            {
                case "DateTime": return egg.Time.Now.ToDateTimeString();
                case "Date": return egg.Time.Now.ToDateString();
                case "Time": return egg.Time.Now.ToTimeString();
                default: throw new Exception($"未知的系统变量'{key}'");
            }
        }
    }
}
